
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import squarify
#各年作品出版数量折线图
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False
file_path = "豆瓣高评分书籍信息-清洗完毕.xlsx.xlsx"
df = pd.read_excel(file_path)
year_counts = df["年份"].value_counts().sort_index()
years = year_counts.index
publish_counts = year_counts.values
plt.figure(figsize=(10, 6))
plt.plot(years, publish_counts, marker='o', linestyle='-', color='g', linewidth=2, markersize=6)
plt.title("各年作品出版数量趋势", fontsize=15)
plt.xlabel("年份", fontsize=12)
plt.ylabel("出版数量（本）", fontsize=12)
plt.grid(alpha=0.3)
plt.tight_layout()
plt.show()
#各价位作品数量直方图
plt.rcParams["font.family"] = ["SimHei", "WenQuanYi Micro Hei", "Heiti TC"]
plt.rcParams["axes.unicode_minus"] = False
file_path = "豆瓣高评分书籍信息-清洗完毕.xlsx.xlsx"
df = pd.read_excel(file_path)
prices = df["价格"]
max_price = prices.max() if not prices.empty else 100
bins = np.arange(0, int(max_price) + 10, 10)
counts, _ = np.histogram(prices, bins=bins)
total = counts.sum()
percents = [f"{(count/total)*100:.1f}%" if total !=0 else "0%" for count in counts]
plt.figure(figsize=(12, 6))
n, bins, patches = plt.hist(prices, bins=bins, color='skyblue', edgecolor='black')
for i, patch in enumerate(patches):
    height = patch.get_height()
    if height > 0:
        plt.text(
            patch.get_x() + patch.get_width()/2,
            height + 0.5,
            f"{counts[i]}\n({percents[i]})",
            ha='center', va='bottom', fontsize=10
        )
plt.title("各价位作品数量分布", fontsize=15)
plt.xlabel("价格区间", fontsize=12)
plt.ylabel("作品数量", fontsize=12)
plt.xticks(bins)
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
print(df[df['价格']>120].sort_values(by='价格',ascending=False).head(20))

#各出版社出版作品数量条形图&评分平均值折线图
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
file_path = "豆瓣高评分书籍信息-清洗完毕.xlsx.xlsx"
df = pd.read_excel(file_path)
publisher_stats = df.groupby('出版社').agg({
    '书名': 'count',
    '评分': 'mean'
}).reset_index()
publisher_stats.columns = ['出版社', '作品数量', '平均评分']
top_publishers = publisher_stats.nlargest(10, '作品数量')
fig, ax1 = plt.subplots(figsize=(12, 6))
x = np.arange(len(top_publishers))
bars = ax1.bar(x, top_publishers['作品数量'], alpha=0.7, color='skyblue', label='作品数量')
ax1.set_xlabel('出版社')
ax1.set_ylabel('作品数量', color='skyblue')
ax1.tick_params(axis='y', labelcolor='skyblue')
for i, bar in enumerate(bars):
    height = bar.get_height()
    ax1.text(bar.get_x() + bar.get_width()/2., height,
             f'{int(height)}', ha='center', va='bottom')
ax2 = ax1.twinx()
line = ax2.plot(x, top_publishers['平均评分'], color='red', marker='o', linewidth=2, label='平均评分')
ax2.set_ylabel('平均评分', color='red')
ax2.tick_params(axis='y', labelcolor='red')
plt.xticks(x, top_publishers['出版社'], rotation=45, ha='right')
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')
plt.title('各出版社作品数量与平均评分对比')
plt.tight_layout()
plt.show()
print("前10名出版社统计：")
print(top_publishers)

#作者作品评分条形图
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
file_path = "豆瓣高评分书籍信息-清洗完毕.xlsx.xlsx"
df = pd.read_excel(file_path)
author_ratings = df.groupby('作者')['评分'].mean().reset_index()
top_authors = author_ratings.nlargest(15, '评分')
plt.figure(figsize=(12, 8))
bars = plt.bar(range(len(top_authors)), top_authors['评分'],
               color='lightcoral', alpha=0.7)
for i, bar in enumerate(bars):
    height = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2., height,
             f'{height:.2f}', ha='center', va='bottom')
plt.title('作者作品平均评分排名（前15名）', fontsize=14, fontweight='bold')
plt.xlabel('作者', fontsize=12)
plt.ylabel('平均评分', fontsize=12)
plt.xticks(range(len(top_authors)), top_authors['作者'], rotation=45, ha='right')
plt.grid(axis='y', alpha=0.3)
plt.tight_layout()
plt.show()
print("作者平均评分排名（前15名）：")
print(top_authors)
#作品评分树状图
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
plt.rcParams['axes.unicode_minus'] = False
file_path = "豆瓣高评分书籍信息-清洗完毕.xlsx.xlsx"
df = pd.read_excel(file_path)
data = df[['书名', '作者', '评分']].dropna(subset=['书名', '评分'])
top_books = data.sort_values('评分', ascending=False).head(20)
labels = [f"{row['书名']}\n{row['作者']}\n{row['评分']:.2f}" for idx, row in top_books.iterrows()]
sizes = top_books['评分'].tolist()
plt.figure(figsize=(16, 8))
squarify.plot(sizes=sizes, label=labels, color=plt.cm.Blues_r(sizes), alpha=0.8, text_kwargs={'fontsize':12})
plt.title('作品评分树状图', fontsize=18, loc='left')
plt.axis('off')
plt.show()
